package com.rupertjones.globalcron.web;

import com.rupertjones.globalcron.domain.Host;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.apache.log4j.Logger;
import org.springframework.security.access.prepost.PreAuthorize;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class EditHostAction extends AbstractFormAction {

    private static final Logger LOG = Logger.getLogger(EditHostAction.class);

    @ValidateNestedProperties({
        @Validate(field = "name", required = true, on = { "SaveOrUpdate" }),
        @Validate(field = "hostname", required = true, on = { "SaveOrUpdate" })
    })
    private Host host;

    @Before(stages = LifecycleStage.BindingAndValidation)
    public void loadAndBind() {
        String id = getContext().getRequest().getParameter("host.id");
        int hostId = Integer.parseInt(id);
        host = getJobService().getHost(hostId);
    }

    public Host getHost() {
        return host;
    }

    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution("/WEB-INF/jsp/edit_host.jsp");
    }

    @HandlesEvent("SaveOrUpdate")
    public Resolution onSave() {
        getJobService().save(host);
        return new ForwardResolution("InfoHosts.action");
    }
}
